package com.example.nettydemo.simple;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 心跳处理器
 *
 * @author SuperWein
 */
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext context, Object event) throws Exception {
        if (event instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) event).state();
            switch (state) {
                case READER_IDLE:
                    log.error("HeartBeat(Server): Read timeout, Client lost response. Force Close Client Connection");
                    // 读超时（空闲时间 默认为16s），自动断开客户端连接
                    context.close();
                    break;
                case WRITER_IDLE:
                    context.channel().writeAndFlush("PING");
                    break;
                case ALL_IDLE:
                    context.channel().writeAndFlush("PING");
                    break;
                default:
                    break;
            }
        } else {
            super.userEventTriggered(context, event);
        }
    }

}
